﻿namespace ShellNavigator.Client.Utils
{
  #region

  using System;
  using System.IO;
  using System.Linq;
  using System.Text.RegularExpressions;
  using System.Xml.Linq;

  using ShellNavigator.Client.Models;

  using FileInfo = System.IO.FileInfo;

  #endregion

  public static class FilterHelper
  {
    #region Public Methods

    public static bool FileInProjectCondition(string fileName, string data)
    {
      XDocument projectFile = XDocument.Load(fileName);
      var items = from item in projectFile.Descendants()
                  where
                    item.Name.LocalName == "Compile" || item.Name.LocalName == "EmbeddedResource"
                    || item.Name.LocalName == "Content"
                  select item;

      var attributes = from item in items
                       let xAttribute = item.Attribute("Include")
                       where xAttribute != null && xAttribute.Value.Contains(data)
                       select item;
      return attributes.Any();
    }

    public static bool ProjectInSolutionCondition(string fileName, string data)
    {
      var buffer = File.ReadAllText(fileName);
      return buffer.Contains(data);
    }

    public static string TextMatch(string fileName, string filter, bool isPlainText, bool isMatchCase)
    {
      if (string.IsNullOrEmpty(filter))
      {
        return string.Empty;
      }

      var fileInfo = new FileInfo(fileName);
      if (fileInfo.Length > 1 * 1024 * 1024)
      {
        return string.Empty;
      }

      var fileContent = File.ReadAllLines(fileName);

      foreach (var line in fileContent)
      {
        if (isPlainText)
        {
          if (isMatchCase)
          {
            if (line.Contains(filter))
            {
              return line;
            }
          }
          else
          {
            if (line.ToLower().Contains(filter.ToLower()))
            {
              return line;
            }
          }
        }
        else
        {
          var regex = new Regex(filter, isMatchCase ? RegexOptions.None : RegexOptions.IgnoreCase);

          if (regex.IsMatch(line))
          {
            return line;
          }
        }
      }

      return string.Empty;
    }

    #endregion
  }
}